package org.nahtanoj.contacts;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;

import org.nahtanoj.contacts.sheet.Sheet;
import org.nahtanoj.contacts.sheet.SheetError;

import com.google.gdata.data.TextContent;
import com.google.gdata.util.ServiceException;

public class DocsContacts {
	private static final Logger log = Logger.getLogger(DocsContacts.class.getName());
	private final HashMap<String, Contact> contacts = new HashMap<String, Contact>();
	private int lastUsedRow = 0;
	private Sheet s;

	public DocsContacts() throws IOException, ServiceException {
		if (this.s == null) {
			this.s = new Sheet("Contacts", "Contacts", 1);
		}
		log.info("" + this.s.getRowCount());
		String colContacts[][] = s.getValues("Last Name", 2, "Validation", s.getRowCount());
		String rowContacts[][] = new String[colContacts[0].length][colContacts.length];

		for (int c = 0; c < colContacts.length; c++) {
			for (int r = 0; r < colContacts[c].length; r++) {
				rowContacts[r][c] = colContacts[c][r];
			}
		}
		for (int i = 0; i < rowContacts.length; i++) {
			String[] contact = rowContacts[i];
			boolean isNull = true;
			for (String f : contact) {
				if (f != null) {
					isNull = false;
				}
			}
			if (isNull == false) {
				this.lastUsedRow = i;
				Contact c = new Contact(contact, i + 2);
				if (contacts.get(c.getHash()) != null) {
					log.warning("Duplicate mail hash:" + c.getLastName() + " " + c.getFirstName());
				}
				contacts.put(c.getHash(), c);
			}
		}
		this.lastUsedRow = this.lastUsedRow + 2; // Header and because count starts at zero
	}

	public void add(Contact c, String contactSync) {
		int r = this.lastUsedRow + 1;
		if (c.getLastName() != null) {
			this.s.setValue("Last Name", r, c.getLastName());
		}
		if (c.getFirstName() != null) {
			this.s.setValue("First Name", r, c.getFirstName());
		}
		if (c.getBusiness() != null) {
			this.s.setValue("Business", r, c.getBusiness());
		}
		if (c.getHome() != null) {
			this.s.setValue("Home", r, c.getHome());
		}
		if (c.getMobile() != null) {
			this.s.setValue("Mobile", r, c.getMobile());
		}
		if (c.getMobile2() != null) {
			this.s.setValue("Mobile 2", r, c.getMobile2());
		}
		if (c.getEmailAddress() != null) {
			this.s.setValue("E-mail Address", r, c.getEmailAddress());
		}
		if (c.getEmail2Address() != null) {
			this.s.setValue("E-mail 2 Address", r, c.getEmail2Address());
		}
		if (c.getHomeStreet() != null) {
			this.s.setValue("Home Street", r, c.getHomeStreet());
		}
		if (c.getHomeStreet2() != null) {
			this.s.setValue("Home Street 2", r, c.getHomeStreet2());
		}
		if (c.getHomeCity() != null) {
			this.s.setValue("Home City", r, c.getHomeCity());
		}
		if (c.getHomeState() != null) {
			this.s.setValue("Home State", r, c.getHomeState());
		}
		if (c.getHomePostalCode() != null) {
			this.s.setValue("Home Postal Code", r, c.getHomePostalCode());
		}
		if (c.getHomeCountry() != null) {
			this.s.setValue("Home Country", r, c.getHomeCountry());
		}
		if (c.getBirthday() != null) {
			this.s.setValue("Birthday", r, c.getBirthday());
		}
		if (c.getAnniversary() != null) {
			this.s.setValue("Anniversary", r, c.getAnniversary());
		}
		if (c.getCategory() != null) {
			this.s.setValue("Category", r, c.getCategory());
		}
		// Hidden fields not populated so update from content field
		if (c.getContactEntry().getContent() != null) {
			this.s.setValue("Notes", r, ((TextContent)c.getContactEntry().getContent()).getContent().getPlainText());
		}
		this.s.setValue("ContactSync", r, contactSync); // Blank so it doesn't get repeated
		this.s.setValue("Validation", r, "New contact from gmail\n" + c.isValid());
		c.setRow(r);
		hashUpdate(c);
		this.lastUsedRow = this.lastUsedRow + 1;
	}

	public boolean contains(Contact m) {
		if (this.contacts.containsKey(m.getHash())) {
			return true;
		}
		List<Contact>matches = new ArrayList<Contact>();
		for (String hash : this.contacts.keySet()) {
			Contact d = this.contacts.get(hash);
			String dLast = d.getLastName(); String dFirst = d.getFirstName();
			String mLast = m.getLastName(); String mFirst = m.getFirstName();
			if (dLast == null) {
				dLast = "";
			}
			if (dFirst == null) {
				dFirst = "";
			}
			if (mLast == null) {
				mLast = "";
			}
			if (mFirst == null) {
				mFirst = "";
			}
			if (dLast.equals(mLast) && dFirst.equals(mFirst)) {
				matches.add(d);
			}
		}
		if (matches.size() == 1) {
			log.info("Matching by name:" + m.getLastName() + " " + m.getFirstName() + " " + m.getHash());
			return true;
		}
		for (Contact c : matches) {
			log.warning("Multiple match:" + c.getLastName() + " " + c.getFirstName());
		}
		return false;
	}

	public HashMap<String, Contact> getContacts() {
		return this.contacts;
	}

	public void hashUpdate(Contact contact) {
		contact.hashUpdate();
		this.s.setValue("Hash", contact.getRow(), contact.getHash());
		this.s.submit();
	}

	public void save() {
		this.s.submit();
	}

	public void updateError(String contactHash, String difference) {
		Contact c = this.contacts.get(contactHash);
		SheetError se = new SheetError(this.s);
		se.addError(c.getRow(), difference);
	}

//	private void add(Contact c) {
//		System.out.println(c);
//		if (c.getCategory() == null || c.getCategory().length() == 0) {
//			log.warning("Category missing:" + c);
//		} else {
//			if (!this.groups.containsKey(c.getCategory())) {
//				groups.put(c.getCategory(), new ArrayList<Contact>());
//			}
//			groups.get(c.getCategory()).add(c);
//		}
//	}

}
